<?php
namespace Common\Org\Pay\alipay;

require_once("lib/alipay_submit.class.php");
require_once("lib/alipay_notify.class.php");

/**
 * 批量转账到其他支付宝账号
 * Class Alipay
 * @package Common\Org\Pay\alipay
 */
class Alipay {
    private $encrypt;

    public function __construct($encrypt='MD5'){
        $this->encrypt = $encrypt;
    }
    
    //配置
    public function __get($name) {
        static $_config = array();
        //返回配置
        if(isset($_config[$name])) return $_config[$name];
        if($name=='all') return $_config;
        //设置配置
        //$config = D('Admin/OnlinePaySet')->getOnlinePayConfig('alipay');
        $config = array();
        $config['partner'] = '2088021755559261';
        $config['key'] = '6mzbum14gntcmyg0fk403si7y9s72g88';
        $config['account'] = 'zhifu@chuguofeng.com';
        $config['account_name'] = '深圳深海投网络科技有限公司';
        $_config['partner'] = $config['partner'];//合作身份者id，以2088开头的16位纯数字
        $_config['key'] = $config['key'];//安全检验码，以数字和字母组成的32位字符
        $_config['seller_email'] = $config['account'];//签约支付宝账号或卖家支付宝帐户
        $_config['account_name'] = $config['account_name'];//签约支付宝账号或卖家支付宝帐户
        //$_config['return_url'] = '';
        //$_config['return_url'] = SITE_URL.'/Fund/recharge_success';//页面跳转同步通知页面路径,要用 http://格式的完整路径，不允许加?id=123这类自定义参数 return_url的域名不能写成http://localhost/create_direct_pay_by_user_php_utf8/return_url.php ，否则会导致return_url执行无效
        $_config['notify_url'] = C('TMPL_PARSE_STRING.__ADMIN__') . '/Pay/alipayNotify'; //服务器异步通知页面路径，要用 http://格式的完整路径，不允许加?id=123这类自
		
        $_config['sign_type'] = $this->encrypt;//签名方式 不需修改
        $_config['input_charset'] = 'utf-8';//字符编码格式 目前支持 gbk 或 utf-8
        $_config['transport'] = 'http';//访问模式,根据自己的服务器是否支持ssl访问，若支持请选择https；若不支持请选择http
        $fileDir = dirname(__FILE__);
        $_config['cacert']    = $fileDir.'/cacert.pem';
        $_config['private_key_path'] = $fileDir.'/key/rsa_private_key.pem';
        $_config['ali_public_key_path'] = $fileDir.'/key/rsa_public_key.pem';

        return $config[$name];
    }

    /**
     * 支付宝登录与绑定
     */
    public function login($id,$type){
        $this->partner;
        $parameter = array(
            "service" => "alipay.auth.authorize",
            "partner" => trim($this->partner),
            "_input_charset"	=> trim(strtolower($this->input_charset)),
            "target_service" => "user.auth.quick.login",
            "return_url" => "http://y.meiliwang.cc/Pay/loginDeal?id=".$id.'&type='.$type,
            "exter_invoke_ip" => "",
            "anti_phishing_key" => "",
            "frame" => "",
            "client_ip" => "",
        );

        //建立请求
        $alipaySubmit = new \AlipaySubmit($this->all);

        return $alipaySubmit->buildRequestForm($parameter,"get", "确认");
    }

    /**
     * 转账接口

     * @param $pay_date 付款日期
     * @param $batch_no 批量付款期次号
     * @param $batch_fee 付款总金额
     * @param $batch_num 付款总笔数
     * @param $detail_data 付款详细数据，付款的详细数据，最多支持1000笔。
     * 格式为：流水号1^收款方账号1^收款账号姓名1^付款金额1^备注说明1|流水号2^收款方账号2^收款账号姓名2^付款金额2^备注说明2。每条记录以“|”间隔
     * @param $account 支付宝账号
     * @param $account_name 支付宝账户名
     * @return \提交表单HTML文本
     */
    public function transfer($pay_date,$batch_no,$batch_fee,$batch_num,$detail_data,$account='',$account_name=''){
        $this->partner;
        $parameter = array(
            "service" => "batch_trans_notify",
            "partner" => trim($this->partner),
            "notify_url"	=> $this->notify_url,//异步通知URL
            "email"	=> $account ? $account : $this->seller_email,//付款方的支付宝账号
            "account_name"	=> $account_name ? $account_name : $this->account_name,//付款方的支付宝账号名
            "pay_date"	=> $pay_date,//付款日期，转账日期，格式YYYYMMDD，如20150729
            "batch_no"	=> $batch_no,//批量付款期次号，11~32位的数字或字母或数字与字母的组合，且区分大小写
            "batch_fee"	=> $batch_fee,//付款总金额，格式：10.01，精确到分
            "batch_num"	=> $batch_num,//付款总笔数，最多1000笔
            "detail_data"	=> $detail_data,//付款详细数据，付款的详细数据，最多支持1000笔。格式为：流水号1^收款方账号1^收款账号姓名1^付款金额1^备注说明1|流水号2^收款方账号2^收款账号姓名2^付款金额2^备注说明2。每条记录以“|”间隔
            "_input_charset"	=> trim(strtolower($this->input_charset))
        );
        //var_dump($parameter);exit;

        //建立请求
        $alipaySubmit = new \AlipaySubmit($this->all);
        return $alipaySubmit->buildRequestForm($parameter,"get", "确认");
    }

    public function setReturnUrl($return_url){
        $this->return_url = $return_url;
    }

    public function setNotifyUrl($notify_url){
        $this->notify_url = $notify_url;
    }

    /**
     * 批量退款
     * @param $refund_date
     * @param $batch_no
     * @param $batch_num
     * @param $detail_data
     * @param string $account
     * @return \提交表单HTML文本
     */
    public function refund($refund_date,$batch_no,$batch_num,$detail_data,$notice_url='',$account=''){
        $this->partner;
        $parameter = array(
            "service" => "refund_fastpay_by_platform_pwd",
            "partner" => trim($this->partner),
            "notify_url"	=> $notice_url ? $notice_url : $this->notify_url,
            "seller_email"	=> $account ? $account : $this->seller_email,
            "refund_date"	=> $refund_date,
            "batch_no"	=> $batch_no,
            "batch_num"	=> $batch_num,
            "detail_data"	=> $detail_data,
            "_input_charset"	=> trim(strtolower($this->input_charset))
        );
        //var_dump($parameter);exit;

        //建立请求
        $alipaySubmit = new \AlipaySubmit($this->all);
        return $alipaySubmit->buildRequestForm($parameter,"get", "确认");
    }

    
    /*
    支付页面
    subject 订单名称
    out_trade_no 商户订单号
    total_fee 付款金额
    body 订单描述
    rc  充值入口
    */
    public function _alipayapi($subject,$out_trade_no,$total_fee,$bank='',$body='',$rc='vip') {
        $this->partner;
        $parameter = array();
        $parameter['service'] = "create_direct_pay_by_user";//指定交易类型为即时到账，create_partner_trade_by_buyer——担保交易
        $parameter['partner'] = $this->partner;//合作商编号，合作身份ID
        $parameter['payment_type']	= "1";
        $parameter['notify_url']	= $this->notify_url;//异步通知返回
        $parameter['return_url']	= $this->return_url;//请求返回地址
        $parameter['seller_email']	= $this->seller_email;//商家账号（邮箱）
        $parameter['out_trade_no']	= $out_trade_no;//商户订单号
        $parameter['subject']	= $subject;//商品名称
        $parameter['total_fee']	= $total_fee;//价格
        $parameter['body']	= $body;//商品简介
        $parameter['defaultbank']	= $bank;
        $parameter['show_url']	= '';
        $parameter['anti_phishing_key']	= '';
        $parameter['exter_invoke_ip']	= '';
        $parameter['_input_charset']	= $this->input_charset;//默认编码

        //建立请求
        $alipaySubmit = new \AlipaySubmit($this->all);

        return $alipaySubmit->buildRequestForm($parameter,"get", "确认");
    }

    //支付宝页面跳转同步通知页面
    public function _return_url($callback='') {
        $this->partner;
        $alipayNotify = new \AlipayNotify($this->all);
        $verify_result = $alipayNotify->verifyReturn();
        if($verify_result && ( $_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS' )) {

            /*$result = array();
            $result['out_trade_no'] = $_REQUEST['out_trade_no'];
            $result['total_fee'] = $_REQUEST['total_fee'];
            $result['body'] = $_REQUEST['body'];*/

            if($callback) $callback();
            //return $result;
            return true;
        }
        return false;
    }
    
    //支付宝服务器异步通知处理
    public function _notify_url($callback) {
        $this->partner;
        $alipayNotify = new \AlipayNotify($this->all);
        $verify_result = $alipayNotify->verifyNotify();

        if($verify_result) {
            echo "success";
            if($callback){
                $callback();
            }
        }else {
            echo "fail";
        }
    }

    
}
?>